//  this library.
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:hktk_app/dao/course_dao.dart';
import 'package:hktk_app/dao/download_dao.dart';
import 'package:hktk_app/dao/subject_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/subject/add_frequency_type.dart';
// import 'package:hktk_app/pages/preview/image_preview_page.dart';
// import 'package:hktk_app/pages/preview/pdf_preview_page.dart';
// import 'package:hktk_app/pages/preview/txt_preview_page.dart';
import 'package:hktk_app/util/dao_util.dart';

import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/widget/home/recommend_item_widget.dart';
// import 'package:hktk_app/widget/home/recommend_item_widget.dart';
import 'package:open_file/open_file.dart';

const Map<String, String> androidMap = {
  "doc": "application/msword",
  "docx":
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "xls": "application/vnd.ms-excel",
  "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
};

const Map<String, String> iosMap = {
  "doc": "com.microsoft.word.doc",
  "xls": "com.microsoft.excel.xls",
};

/// 推荐区资源组件显示
class ResourceItemWidget extends StatelessWidget {
  /// 标题
  final String title;

  /// 人数（观看/做过）
  final int num;

  /// 副标题，副的相关数据
  final String subtitle;

  /// 栏目id
  final String columnId;

  /// 免费标志，true：免费/购买，false：未购买
  final bool free;

  /// 资料对应路径
  final String resUrl;

  /// 资料对应id
  final String resId;

  /// 是否是视频相关的资料。true：是，false：不是。控制添加观看次数方法
  final bool videoRes;

  const ResourceItemWidget({
    super.key,
    required this.title,
    required this.num,
    required this.subtitle,
    required this.columnId,
    required this.free,
    required this.resUrl,
    required this.resId,
    required this.videoRes,
  });

  @override
  Widget build(BuildContext context) {
    String type = _getResType();
    return RecommendItemWidget(
      title: title,
      num: num,
      subtitle: subtitle,
      type: type,
      showPaper: false,
      btnType: !free,
      btnStr: free ? "观看" : "预览",
      onTapFun: _onTapFun,
      resUrl: resUrl,
    );
    // return Container();
  }

  /// 获取资料类型方法
  String _getResType() {
    return resUrl.substring(resUrl.lastIndexOf(".") + 1);
  }

  /// 点击方法
  void _onTapFun(BuildContext context, String type) {
    _viewResFun(context: context, type: type, showTips: !free);
  }

  /// 查看资源文件方法
  void _viewResFun({
    required BuildContext context,
    required String type,
    required bool showTips,
  }) {
    bool showToast = false;
    String url = coverHead + resUrl;
    switch (type) {
      case "pdf":
        Navigator.pushNamed(context, "/preview-pdf",arguments: {
              "url": url,
              "name": title,
              "type": type,
              "showTips": showTips,
              "columnId": columnId,
              "resId": resId,
              "videoRes": videoRes,
          "netWork":true
        });
        break;
      case "doc":
      case "docx":
      case "xls":
      case "xlsx":
        if (!showTips) {
          _showDocFun(type: type, url: url, context: context);
        } else {
          ToastUtil.show(context: context, msg: "不支持预览");
        }
        break;
      case "jpg":
      case "jpeg":
      case "png":
      Navigator.pushNamed(context, "/preview-img",arguments: {
        "url": url,
        "name": title,
        "type": type,
        "showTips": showTips,
        "columnId": columnId,
        "resId": resId,
        "videoRes": videoRes,
      });
        break;
      case "txt":
        Navigator.pushNamed(context, "/preview-txt",arguments: {
          "url": url,
          "name": title,
          "type": type,
          "showTips": showTips,
          "columnId": columnId,
          "resId": resId,
          "videoRes": videoRes,
        });

        break;
      default:
        showToast = true;
    }
    if (showToast) {
      ToastUtil.show(context: context, msg: "不支持的文件类型");
    }
  }

  /// 显示打开本地应用软件
  void _showDocFun({
    required String type,
    required String url,
    required BuildContext context,
  }) async {
    // 打开加载框
    ToastUtil.loadingBoxShow(context);
    _futureWord(type: type, url: url).then((Map<String, dynamic> map) {
      // 关闭加载框
      ToastUtil.loadingBoxRemove();
      if (!map["suc"]) {
        ToastUtil.show(context: context, msg: map["msg"]);
      }
    });
  }

  /// 打开对应本地文件
  Future<Map<String, dynamic>> _futureWord({
    required String type,
    required String url,
  }) async {
    Map<String, dynamic> map = {};
    try {
      // 下载文件
      File file = await DownloadDao.downloadTemporaryFile(
        url: url,
        fileName: "$title.$type",
      );
      if (!videoRes) {
        // 增加查看次数
        await SubjectDao.addFrequency(
          type: AddFrequencyType.watch_time,
          id: resId,
        );
      } else {
        // 增加查看次数（视频）
        await CourseDao.addFrequency(
          resId: resId,
        );
      }

      // 打开对应本地文件
      String fileType;
      if (Platform.isIOS) {
        String sType = type;
        if (type == "docx") sType = "doc";
        if (type == "xlsx") sType = "xls";
        fileType = iosMap[sType]!;
      } else {
        fileType = androidMap[type]!;
      }
      OpenResult result = await OpenFile.open(file.path, type: fileType);

      if (result.type == ResultType.noAppToOpen) {
        map["suc"] = false;
        map["msg"] = "找不到打开此文件的app";
      } else if (result.type == ResultType.permissionDenied) {
        map["suc"] = false;
        map["msg"] = "权限被拒绝";
      } else if (result.type == ResultType.error ||
          result.type == ResultType.fileNotFound) {
        map["suc"] = false;
        map["msg"] = "未知错误，请重试";
      } else {
        map["suc"] = true;
      }
    } catch (e) {
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        map["msg"] = e.msg;
      }
    }
    return map;
  }
}
